package main;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;

import DBClasses.EGSImage;
import DBClasses.Game;
import DBClasses.GameType;

@SuppressWarnings("serial")
public class AddGame extends BaseServlet
{
	@SuppressWarnings({ "unused", "unchecked" })
	@Override
	protected void action(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException
	{
		Float price = null;
		String change = null;
		String cat = null;
		List<String> scrns = new ArrayList<String>();
		String header = null;
		String text = null;
		String id = "";
		byte[] img_buf = new byte[0];
		PersistenceManager manager = PMF.get().getPersistenceManager();
		try
		{
			ServletFileUpload upload = new ServletFileUpload();
			upload.setSizeMax(10000000);
			FileItemIterator iterator = upload.getItemIterator(req);
			while (iterator.hasNext())
			{
				FileItemStream item = iterator.next();
				InputStream stream = item.openStream();
				byte[] buffer = new byte[1000000];
				int len;
				len = stream.read(buffer);
				if (item.getFieldName().equals("price_txt"))
				{
					if (len > 0)
						try
						{
							price = Float
									.parseFloat(new String(buffer, 0, len));
						} catch (Exception ex)
						{
							price = null;
						}
					continue;
				}
				if (item.getFieldName().equals("change"))
				{
					if (len > 0)
						change = new String(buffer, 0, len);
					else
						change = "";
					continue;
				}
				if (item.getFieldName().equals("category_txt"))
				{
					if (len > 0)
						cat = new String(buffer, 0, len);
					else
						cat = "";
					continue;
				}
				if (item.getFieldName().equals("header_txt"))
				{
					if (len > 0)
						header = new String(buffer, 0, len);
					else
						header = "";
					continue;
				}
				if (item.getFieldName().equals("text_txt"))
				{
					if (len > 0)
						text = new String(buffer, 0, len);
					else
						text = "";
					continue;
				}
				if (!item.isFormField())
				{
					if (len > 0)
					{
						img_buf = new byte[1000000];
						for (int i = 0; i < len; i++)
							img_buf[i] = buffer[i];
						int cur_ln = stream.read(buffer);
						while (cur_ln > 0)
						{
							for (int i = len; i < len + cur_ln; i++)
								img_buf[i] = buffer[i - len];
							len += cur_ln;
							cur_ln = stream.read(buffer);
						}
						EGSImage newe_img = new EGSImage(img_buf);
						manager.makePersistent(newe_img);
						
						if (item.getFieldName().contains("scr"))
							scrns.add(newe_img.getId().toString());
						else
							id = newe_img.getId().toString();
					}
				}
			}
		} catch (Exception ex)
		{
			resp.getWriter().write("img");
			return;
		}
		if (header == null || header.equals(""))
		{
			resp.getWriter().write("header");
			return;
		} else
		{
			if (text == null || text.equals(""))
			{
				resp.getWriter().write("text");
				return;
			} else
			{
				if (price == null)
				{
					resp.getWriter().write("price");
					return;
				} else
				{
					List<GameType> gts = (List<GameType>) manager.newQuery(
							"select from " + GameType.class.getName()
									+ " where name == '" + cat + "'").execute();

					Game game = null;
					String result = "fail";
					if (change == null || change == "")
					{
						game = new Game(header, price.floatValue(), gts.get(0)
								.getName(), ((UserView) req.getSession()
								.getAttribute("user")).getUser().getLogin(),
								text.toString(), id, scrns);
						result = "success";
					} else
					{
						List<Game> games = (List<Game>) manager.newQuery(
								"select from " + Game.class.getName()
										+ " where id == "
										+ req.getParameter("id").toString())
								.execute();
						if (games != null && games.size() > 0)
						{
							game = games.get(0);
							game.setDescription(req.getParameter("text_txt"));
							game.setGameType(req.getParameter("category_txt"));
							game.setPrice(Float.parseFloat(req
									.getParameter("price_txt")));
							game.setImg(id);
							if(scrns.size()>0)
								game.setScrns(scrns);
							result = "success";
						}
					}
					manager.makePersistent(game);
					manager.close();
					if (change == null || change == "")
					{
						resp.sendRedirect("/categories.jsp");
					} else
					{
						resp.getWriter().write(result);
					}
				}
			}
		}
	}
}
